/*
 * @Description:
 * @Version: 2.0
 * @Autor: snzo.chen
 * @Date: 2023-05-18 09:22:01
 * @LastEditors: snzo.chen
 * @LastEditTime: 2023-05-26 14:36:08
 */
import { HttpClient } from '@angular/common/http';
import { Inject, Injectable } from '@angular/core';
import { AuthService } from '../auth/auth.service';
import { API_CONFIG_UC } from './services.module';
import { Observable, map } from 'rxjs';
import { AnyJson } from './data-types/common.type';
import { StorageService } from './storage.service';
import Util from '../../../public/utils/util';
declare var aesUtil: any;

@Injectable({
  providedIn: 'root',
})
export class UcService {
  constructor(
    private http: HttpClient,
    private authService: AuthService,
    private stoageServe: StorageService,
    @Inject(API_CONFIG_UC) private uc: string
  ) {}

  /**
   * 用户注册
   */
  ValidateAddUser(params: AnyJson): Observable<AnyJson> {
    const encryptKey = '1kQdPy54X23VjXT7f9nl6d4f2m8238ET';
    const aesRandomKey = aesUtil.getKey();
    const aesKey = aesUtil.encrypt(aesRandomKey, encryptKey);
    const data = aesUtil.encrypt(params, aesRandomKey);
    const body = new URLSearchParams();
    body.set('aesKey', aesKey);
    body.set('data', data);
    body.set('timestamp', new Date().getTime().toString());
    const headers = {
      'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
    };
    return this.http
      .post(this.uc + '/api/uc/user/ValidateAddUser', body, { headers })
      .pipe(map((res) => res as AnyJson));
  }

  /**
   * 获取用户信息
   */
  queryCardInfo(params: AnyJson, token: string): Observable<AnyJson> {
    const body = Util.formatSearchParams(params);
    const headers = {
      'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
      Authorization: token,
    };
    return this.http
      .post(this.uc + '/api/uc/user/queryCardInfo', body, { headers })
      .pipe(map((res) => res as AnyJson));
  }

  /**
   * 发送手机号验证码  1=注册短信类型,2=登陆短信类别，3=更新用户短信类别
   */
  sendSms(phone: string, params: AnyJson): Observable<AnyJson> {
    const body = Util.formatSearchParams(params);
    const headers = {
      'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
    };
    return this.http
      .post(this.uc + '/api/common/sendSms/' + phone, body, { headers })
      .pipe(map((res) => res as AnyJson));
  }

  /**
   * 验证token
   */
  isToken(): Observable<AnyJson> {
    const headers = {
      Authorization: this.authService.token,
    };
    return this.http
      .post(this.uc + '/api/uc/common/isToken', null, { headers })
      .pipe(map((res) => res as AnyJson));
  }

  /**
   * 上传头像
   * @param body
   * @returns
   */
  uploadUserImg(body: AnyJson): Observable<AnyJson> {
    return this.http
      .post(this.uc + '/api/uc/user/uploadUserImg', body)
      .pipe(map((res) => res as AnyJson));
  }
}
